﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LN = Lucene.Net;

namespace LuceneTest
{
    class Program
    {
        const string path = @"E:\工作\中青旅\TestApps\LuceneTest\LuceneTest\bin\Debug\Index";

        static void Main(string[] args)
        {
//            createIndex("Manhunt Ends With Capture of Boston Bombing Suspect", @"Police and Federal Bureau of Investigation agents converged on a house here around 7 p.m., officials said. Before taking him into custody nearly two hours later, authorities exchanged gunfire with Dzhokhar Tsarnaev, who was found hiding in a boat, covered in blood, by a resident checking on his backyard. Police said Mr. Tsarnaev had been wounded in an early-morning firefight with police. They said it was unclear if he suffered additional injuries in the shootout at the boat.
//""CAPTURED!!! The hunt is over,"" tweeted the Boston Police Department. ""The search is done. The terror is over."" Mr. Tsarnaev is one of two brothers alleged to have exploded two homemade bombs at the marathon Monday, killing three people and injuring more than 175. He was taken to a hospital and listed in serious condition. The arrest capped a violent overnight spree that began with the fatal shooting of a campus police officer at the Massachusetts Institute of Technology and included a police chase through Boston suburbs. The brothers, carrying an arsenal of explosives, fled police before dawn Friday in a stolen Mercedes and hurled pipe bombs in a firefight with police, which left one officer injured.
//The older brother, 26-year-old Tamerlan Tsarnaev, wearing what appeared to be an explosive vest, was shot by police and died shortly after, while the younger brother narrowly escaped—after first running over Tamerlan's body with the Mercedes, officials said.
//Authorities gave no indication of what motivated the brothers. Their family roots stretch to the Russian republic of Chechnya, which has been a wellspring of terrorism over the years.");
//            createIndex("What We Know About the Boston Bombing Manhunt", @"Authorities captured a 19-year-old college student suspected in the deadly Boston Marathon bombings after one of the biggest manhunts in U.S. history paralyzed an entire metropolis.
//THE SUSPECTS: 
//U.S. authorities identified two suspects in the Boston Marathon bombings. They were brothers of Chechen background: Tamerlan Tsarnaev, 26 years old, and Dzhokhar Tsarnaev, 19. The older brother was killed in a confrontation with police in Watertown, Mass. The younger brother was captured and in serious condition late Friday after police and FBI converged on a Watertown house. THEIR BACKGROUND: 
//Dzhokhar Tsarnaev is a student at the University of Massachusetts, Dartmouth, a university spokesman said. He attended Cambridge Rindge and Latin School in Cambridge, Mass. Tamerlan Tsarnaev, who spent time as an amateur boxer, attended Bunker Hill Community College as a part-time student for three semesters.
//The family of the suspected bombers arrived in Cambridge, Mass. around 2002. They had come to the U.S. to seek refuge from the war in Chechnya. The patriarch, Anzor Tsarnaev, was an auto mechanic. About two years ago, the father was stricken with brain cancer, and departed to Germany last year for treatment, according to a friend of the family.");

            createCNIndex("中超-皮库35秒闪袭王永珀两记世界波 鲁能3-1辽宁", @"新浪体育讯　北京时间4月20日，2013赛季中超[微博]联赛第6轮展开争夺，山东鲁能[微博]主场迎战辽宁宏运[微博]。第35秒，皮斯库里奇左脚远射破门。第20分钟，皮库助攻王永珀[微博]右脚重炮轰门得手。第24分钟，王永珀任意球直接破门。2分钟后，詹姆斯扳回一球。第42分钟，杜威[微博]受伤离场。90分钟的激战，山东鲁能主场3-1击败辽宁宏运，取得主场4连胜，辽足遭遇首败。
　　中超历史上双方交锋过16次，鲁能对辽足11胜2平3负形成较明显优势；上赛季辽足客场1-1战平鲁能，结束了中超以来客场对鲁能的7连败；而值得关注的是：辽足客场7战鲁能，有6场均取得过入球。本赛季两支球队的状态都非常不错，上轮鲁能在上半场形势占尽优势的情况下客场被申花[微博]翻盘，最终1-2落败，终结了开局4连胜走势。辽足主场3-1击败绿城后，新赛季来2胜3平保持不败，埃杜5轮打入5球。人员方面，鲁能吕征[微博]因伤缺阵，马塞纳淡出首发，杨旭[微博]和皮斯库里奇首发出场，周海滨伤愈复出取代崔鹏[微博]。辽足詹姆斯回归与埃杜搭档锋线。赛前双方球员集体为雅安地震遇难者默哀，鲁能球迷更是打出“雅安加油”的横幅");
            createCNIndex("中超-埃神戴帽郜林助攻帽子戏法 恒大6-1狂胜亚泰", @"新浪体育讯　北京时间4月20日广州消息，2013赛季中超联赛第6轮继续展开争夺，广州恒大主场迎战长春亚泰。埃尔克森本场比赛上演了“帽子戏法”，孔卡、金英权和穆里奇破门锦上添花。卡洛斯单刀球破门，为长春亚泰挽回一点颜面。最终经过90分钟的激战，广州恒大队在主场以6比1大胜长春亚泰。
　　双方中超联赛历史交锋方面，恒大3胜2平3负，与亚泰难分伯仲。但前五轮两队表现形成强烈对比。广州恒大队少赛1场，恒大距离榜首的青岛中能只有3分，回到主场迎战5轮不胜的长春亚泰，恒大自然希望尽快解决战斗，而不是再拖到下半场才发力，毕竟下周中还有亚冠任务。巴西射手埃尔克森前4场联赛打进7球，势不可挡。上赛季恒大双杀长春，其中在主场4比0大获全胜，本场比赛恒大获胜基本没有悬念。");

            searchCN("中超");
            Console.Read();
        }

        static void createIndex(string title, string content)
        {
            bool isNew = false;
            var dir = new LN.Store.SimpleFSDirectory(new System.IO.DirectoryInfo(path));
            if (!LN.Index.IndexReader.IndexExists(dir))
            {
                isNew = true;
            }

            LN.Analysis.Standard.StandardAnalyzer analyzer = new LN.Analysis.Standard.StandardAnalyzer(LN.Util.Version.LUCENE_30);
            LN.Index.IndexWriter iw = new LN.Index.IndexWriter(dir, analyzer, isNew, LN.Index.IndexWriter.MaxFieldLength.LIMITED);
            LN.Documents.Document document = new LN.Documents.Document();
            document.Add(new LN.Documents.Field("title", title, LN.Documents.Field.Store.YES, LN.Documents.Field.Index.ANALYZED, LN.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
            document.Add(new LN.Documents.Field("content", content, LN.Documents.Field.Store.YES, LN.Documents.Field.Index.ANALYZED, LN.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
            iw.AddDocument(document);
            iw.Optimize();
            iw.Dispose();
        }

        static void createCNIndex(string title, string content)
        {
            bool isNew = false;
            var dir = new LN.Store.SimpleFSDirectory(new System.IO.DirectoryInfo(path));
            if (!LN.Index.IndexReader.IndexExists(dir))
            {
                isNew = true;
            }

            LN.Analysis.Cn.ChineseAnalyzer analyzer = new LN.Analysis.Cn.ChineseAnalyzer();
            LN.Index.IndexWriter iw = new LN.Index.IndexWriter(dir, analyzer, isNew, LN.Index.IndexWriter.MaxFieldLength.LIMITED);
            LN.Documents.Document document = new LN.Documents.Document();
            document.Add(new LN.Documents.Field("title", title, LN.Documents.Field.Store.YES, LN.Documents.Field.Index.ANALYZED, LN.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
            document.Add(new LN.Documents.Field("content", content, LN.Documents.Field.Store.YES, LN.Documents.Field.Index.ANALYZED, LN.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
            iw.AddDocument(document);
            iw.Optimize();
            iw.Dispose();
        }

        static void createPanGuIndex(string title, string content)
        {
            //bool isNew = false;
            //var dir = new LN.Store.SimpleFSDirectory(new System.IO.DirectoryInfo(path));
            //if (!LN.Index.IndexReader.IndexExists(dir))
            //{
            //    isNew = true;
            //}

            //LN.Analysis.Analyzer analyzer = new LN.Analysis.PanGu.PanGuAnalyzer();
            //LN.Index.IndexWriter iw = new LN.Index.IndexWriter(dir, analyzer, isNew, LN.Index.IndexWriter.MaxFieldLength.LIMITED);
            //LN.Documents.Document document = new LN.Documents.Document();
            //document.Add(new LN.Documents.Field("title", title, LN.Documents.Field.Store.YES, LN.Documents.Field.Index.ANALYZED, LN.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
            //document.Add(new LN.Documents.Field("content", content, LN.Documents.Field.Store.NO, LN.Documents.Field.Index.ANALYZED, LN.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
            //iw.AddDocument(document);
            //iw.Optimize();
            //iw.Dispose();
        }


        static void search(string keyWord)
        {
            List<Item> results = new List<Item>();
            var dir = new LN.Store.SimpleFSDirectory(new System.IO.DirectoryInfo(path));
            LN.Analysis.Standard.StandardAnalyzer analyzer = new LN.Analysis.Standard.StandardAnalyzer(LN.Util.Version.LUCENE_30);
            LN.Search.IndexSearcher searcher = new LN.Search.IndexSearcher(dir);
            LN.QueryParsers.MultiFieldQueryParser parser = new LN.QueryParsers.MultiFieldQueryParser(LN.Util.Version.LUCENE_30, new string[] { "title", "content" }, analyzer);
            LN.Search.Query query = parser.Parse(keyWord);
            LN.Search.TopScoreDocCollector collector = LN.Search.TopScoreDocCollector.Create(10, true);
            searcher.Search(query, collector);
            var hits = collector.TopDocs().ScoreDocs;

            int numTotalHits = collector.TotalHits;
            Console.WriteLine("查找 " + keyWord + " ...共找到 " + numTotalHits + "个匹配的文档");

            //以后就可以对获取到的collector数据进行操作
            for (int i = 0; i < hits.Count(); i++)
            {
                var hit = hits[i];
                LN.Documents.Document doc = searcher.Doc(hit.Doc);
                LN.Documents.Field titleField = doc.GetField("title");
                LN.Documents.Field contentField = doc.GetField("content");

                Console.WriteLine(titleField.StringValue + "[" + contentField.StringValue + "]，匹配指数：" + Math.Round(hit.Score * 100, 2) + "%");
                Console.WriteLine(string.Empty);
            }
            searcher.Dispose();
        }

        static void searchCN(string keyWord)
        {
            List<Item> results = new List<Item>();
            var dir = new LN.Store.SimpleFSDirectory(new System.IO.DirectoryInfo(path));
            LN.Analysis.Cn.ChineseAnalyzer analyzer = new LN.Analysis.Cn.ChineseAnalyzer();
            LN.Search.IndexSearcher searcher = new LN.Search.IndexSearcher(dir);
            LN.QueryParsers.MultiFieldQueryParser parser = new LN.QueryParsers.MultiFieldQueryParser(LN.Util.Version.LUCENE_30, new string[] { "title", "content" }, analyzer);
            LN.Search.Query query = parser.Parse(keyWord);
            LN.Search.TopScoreDocCollector collector = LN.Search.TopScoreDocCollector.Create(10, true);
            searcher.Search(query, collector);
            var hits = collector.TopDocs().ScoreDocs;

            int numTotalHits = collector.TotalHits;
            Console.WriteLine("查找 " + keyWord + " ...共找到 " + numTotalHits + "个匹配的文档");

            //以后就可以对获取到的collector数据进行操作
            for (int i = 0; i < hits.Count(); i++)
            {
                var hit = hits[i];
                LN.Documents.Document doc = searcher.Doc(hit.Doc);
                LN.Documents.Field titleField = doc.GetField("title");
                LN.Documents.Field contentField = doc.GetField("content");

                Console.WriteLine(titleField.StringValue + "[" + contentField.StringValue + "]，匹配指数：" + Math.Round(hit.Score * 100, 2) + "%");
                Console.WriteLine(string.Empty);
            }
            searcher.Dispose();
        }

    }

    public class Item
    {
        public string Title { get; set; }
        public string Content { get; set; }
    }
}
